package com.fanqwz.hexieshe.data;

import android.content.Context;

import com.fanqwz.hexieshe.data.common.Utils;
import com.fanqwz.hexieshe.data.entity.wp.Post;
import com.fanqwz.hexieshe.data.entity.wp.Taxonomy;
import com.fanqwz.hexieshe.domain.Article;
import com.fanqwz.hexieshe.domain.Category;
import com.fanqwz.hexieshe.domain.Comment;
import com.fanqwz.hexieshe.data.API.wp.WPInterface;
import com.fanqwz.hexieshe.data.entity.wp.mapper.EntityMapper;
import com.fanqwz.hexieshe.domain.HeadLine;
import com.fanqwz.hexieshe.domain.repository.Repository;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.Observable;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by fanqw on 2017/6/29.
 */

@Singleton
public class HXSRepository implements Repository {
    WPInterface wp;
    EntityMapper entityMapper;
    private final Context context;

    Interceptor interceptor = chain -> {
        okhttp3.Response r = chain.proceed(chain.request());
        return r.newBuilder().build();
    };

    @Inject
    HXSRepository(Context context, EntityMapper entityMapper) {
        this.entityMapper = entityMapper;
        this.context = context;

        OkHttpClient client = new OkHttpClient().newBuilder()
                .addNetworkInterceptor(interceptor)
                .build();
        Retrofit retrofit = new Retrofit.Builder(

        )
                .baseUrl("https://www.hexieshe.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        wp = retrofit.create(WPInterface.class);

    }

    @Override
    public Observable<List<HeadLine>> headlines(int page, String category, String tag) {
        return Observable.create(emitter -> {
            Call<List<com.fanqwz.hexieshe.data.entity.wp.Post>> posts = wp.getTopics(page, category, tag);
            posts.enqueue(new Callback<List<com.fanqwz.hexieshe.data.entity.wp.Post>>() {
                @Override
                public void onResponse(Call<List<com.fanqwz.hexieshe.data.entity.wp.Post>> call, Response<List<com.fanqwz.hexieshe.data.entity.wp.Post>> response) {
                    emitter.onNext(entityMapper.transformHeadline(response.body()));
                    emitter.onComplete();
                }

                @Override
                public void onFailure(Call<List<com.fanqwz.hexieshe.data.entity.wp.Post>> call, Throwable t) {
                    emitter.onError(t);
                }
            });
        });
    }

    @Override
    public Observable<Article> article(long id) {
        return Observable.create(emitter -> {
            Call<Post> post = wp.getPost(id);
            post.enqueue(new Callback<Post>() {
                @Override
                public void onResponse(Call<Post> call, Response<Post> response) {
                    Article article = entityMapper.transform(response.body());
                    article.setContent(Utils.webContentImageScaleToFitScreen(article.getContent()));
                    emitter.onNext(article);
                    emitter.onComplete();
                }

                @Override
                public void onFailure(Call<Post> call, Throwable throwable) {
                    emitter.onError(throwable);
                }
            });
        });
    }

    @Override
    public Observable<List<Comment>> comments(long articleID) {
        return Observable.create(emitter -> {
            Call<List<com.fanqwz.hexieshe.data.entity.wp.Comment>> comments = wp.getComment(articleID);
            comments.enqueue(new Callback<List<com.fanqwz.hexieshe.data.entity.wp.Comment>>() {
                @Override
                public void onResponse(Call<List<com.fanqwz.hexieshe.data.entity.wp.Comment>> call, Response<List<com.fanqwz.hexieshe.data.entity.wp.Comment>> response) {
                    emitter.onNext(entityMapper.transformComments(response.body()));
                    emitter.onComplete();
                }

                @Override
                public void onFailure(Call<List<com.fanqwz.hexieshe.data.entity.wp.Comment>> call, Throwable throwable) {
                    emitter.onError(throwable);
                }
            });
        });
    }

    @Override
    public Observable<List<Category>> categories() {
        return Observable.create(emitter -> {
            Call<List<Taxonomy>> category = wp.getCategorys();
            category.enqueue(new Callback<List<Taxonomy>>() {
                @Override
                public void onResponse(Call<List<Taxonomy>> call, Response<List<Taxonomy>> response) {

                    List<Category> origins = entityMapper.transformCategory(response.body());
                    List<Category> categories = new ArrayList<Category>(origins.size() + 1);
                    Category mainCat = new Category();
                    mainCat.setId(0);
                    mainCat.setDisplayName(context.getString(R.string.main_page));
                    categories.add(mainCat);
                    categories.addAll(origins);
                    emitter.onNext(categories);
                    emitter.onComplete();
                }

                @Override
                public void onFailure(Call<List<Taxonomy>> call, Throwable throwable) {
                    emitter.onError(throwable);
                }
            });
        });
    }

    @Override
    public void commitComment(long articleID, String comment) {
        throw new RuntimeException("UnImplemented");
    }
}
